package com.sunday.fangbeibei.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.sunday.fangbeibei.R;
import com.sunday.fangbeibei.adapter.ImageAdapter;
import com.sunday.fangbeibei.cache.ApplicationCache;
import com.sunday.fangbeibei.constants.ApplicationConstants;
import com.sunday.fangbeibei.http.HttpResponseInterface;
import com.sunday.fangbeibei.http.HttpTool;
import com.sunday.fangbeibei.orm.BaseResult;
import com.sunday.fangbeibei.tool.MethodUtil;
import com.sunday.fangbeibei.widget.ActionSheet;
import com.sunday.fangbeibei.widget.ActionSheet.ActionSheetListener;

/**
 * 新增动态
 * @author 晨曦
 *
 */
public class DynamicAddActivity extends BaseFragmentActivity implements OnClickListener,OnItemClickListener,ActionSheetListener,HttpResponseInterface{

	
	private List<String> lists;
	private ImageAdapter adapter;
	private EditText content;

	private File image;
	
	private int current;
	
	
	@Override
	protected void createActivity(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.dynamic_add_layout);
		loadView();
	}

	private void loadView(){
		
		lists=new ArrayList<String>();
		
		GridView gridview=(GridView) findViewById(R.id.gridview);
		adapter=new ImageAdapter(this,lists);
		gridview.setAdapter(adapter);
		gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		gridview.setOnItemClickListener(this);
		
		content=(EditText) findViewById(R.id.content);
		
		TextView right=(TextView) findViewById(R.id.right);
		right.setOnClickListener(this);
		ImageView back=(ImageView) findViewById(R.id.back);
		back.setOnClickListener(this);
		
		gridview.setAdapter(adapter);
	}

	@Override
	public void onResponse(int requsetCode, boolean resultStatus, Object result) {
		// TODO Auto-generated method stub
		switch(requsetCode){
		case 0:
			disMiss();
			BaseResult<String> result1=(BaseResult<String>) result;
			if(resultStatus){
				if(current==lists.size()){
					lists.add(result1.getResult());
				}else{
					lists.set(current, result1.getResult());
				}
				adapter.notifyDataSetChanged();
				
			}else{
				Toast.makeText(mContext, "上传图片失败！", Toast.LENGTH_SHORT).show();
			}
			break;
		case 1:
			if(resultStatus){
				Toast.makeText(mContext, "发表成功！", Toast.LENGTH_SHORT).show();
				finish();
			}else{
				Toast.makeText(mContext, "发表失败！", Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}

	@Override
	public void onFailure() {
		// TODO Auto-generated method stub
		disMiss();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		current=position;
		setTheme(R.style.ActionSheetStyleIOS7);
		ActionSheet.createBuilder(this, getSupportFragmentManager())
		.setCancelButtonTitle("取消")
		.setOtherButtonTitles("拍照", "从相册选择")
		.setCancelableOnTouchOutside(true).setListener(this).show();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.back:
			finish();
			break;
		case R.id.right:
			if(content.getText().toString().equals("")){
				Toast.makeText(mContext, "帖子内容不能为空！", Toast.LENGTH_SHORT).show();
				return;
			}
			
			String ss="";
			for(String img:lists){
				if(ss.equals("")){
					ss=ss+img;
				}else{
					ss=ss+","+img;
				}
			}
			
			RequestParams params=new RequestParams();
			params.put("memberId", ApplicationCache.INSTANCE.getUserInfo().getId());
			params.put("simpleContent", content.getText().toString());
			params.put("images", ss);
			HttpTool.HttpPost(1, mContext, ApplicationConstants.SERVER_URL+"/mobi/blog/save", params, this, new TypeToken<BaseResult>() {
			}.getType());
			
			break;
				
		}
	}

	@Override
	public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onOtherButtonClick(ActionSheet actionSheet, int index) {
		// TODO Auto-generated method stub
		if(index==0){
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			image=new File(Environment.getExternalStorageDirectory(),"temp.jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(image));
            startActivityForResult(intent, 2);
		}else if(index==1){
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			intent.setType("image/*");
			
		    if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){                  
		        startActivityForResult(intent, 4);    
			}else{          
		        startActivityForResult(intent, 3);   
			}   
		
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, data);
		if(arg1==RESULT_OK){
			if(arg0==3){
				Uri selectedImage = data.getData();
	            String[] filePathColumn = { MediaStore.Images.Media.DATA };
	 
	            Cursor cursor = getContentResolver().query(selectedImage,
	                    filePathColumn, null, null, null);
	            cursor.moveToFirst();
	 
	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            String picturePath = cursor.getString(columnIndex);
	            cursor.close();
	            
		        image=new File(picturePath);
		        
			}else if(arg0==4){
				//kitkat
				image=new File(MethodUtil.getPath(mContext, data.getData()));
				
			}
			
			if(image==null){
				return;
			}
			try {
				show("正在上传");
				RequestParams params=new RequestParams();
				params.put("image", image);
				HttpTool.HttpPost(0, mContext, "http://festival.o2o2m.com/mobi/active/addCommentImage", params, this, new TypeToken<BaseResult<String>>() {
				}.getType());
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				disMiss();
			}

		}
	}

}
